<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>列表渲染</title>

    <script src="../js/vue.js">

    </script>
</head>
<body>

<div id="root">
    <input v-model="keyword" placeholder="请输入姓名"/>
    <button @click="sortType=2">年龄升序</button>
    <button @click="sortType=1">年龄降序</button>
    <button @click="sortType=0">原顺序</button>

    <ul>
        <li v-for="(item,index) in resultsComputed" :key="item.id">
            {{item.name}}的年龄是{{item.age}}
        </li>
    </ul>


</div>

<script type="text/javascript">
    Vue.config.printWarnings = false;
    const vm = new Vue({
        el: '#root',
        data: {
            keyword: '',
            sortType: 0,
            persons: [{
                name: '张三',
                age: 18,
                id: 1,
            }, {
                name: '李四',
                age: 20,
                id: 2,
            }, {
                name: '王五',
                age: 23,
                id: 3,
            }, {
                name: '李五',
                age: 12,
                id: 4,
            }],
            results: []
        },
        methods: {},
        computed: {
            // 使用计算属性实现列表过滤
            // 此方法中使用了sortType和keyword，所以当sortType或者keyword的值发生改变，都会重新调用此方法
            resultsComputed: function () {
                let ts = this.persons.filter(item => item.name.indexOf(this.keyword) > -1);
                if (this.sortType) {
                    ts.sort((a, b) => {
                        return this.sortType === 2 ? a.age - b.age : b.age - a.age;
                    })
                }
                return ts;
            },
        },
        watch: {
            // 使用watch实现列表过滤
            keyword: {
                immediate: true,
                handler(val) {
                    this.results = this.persons.filter(item => item.name.indexOf(val) > -1);
                }
            }
        }
    });

</script>
</body>

</html>